# coding=utf-8
# 全世界最帅的帅哥
import json
from flask_restful import reqparse
from ysgg1_club_comment.modules.subject_label import SubjectLabel
from ysgg1_club_comment.modules import db
from flask import current_app, request
from sqlalchemy.exc import SQLAlchemyError, OperationalError
from ..comment.enums.result_enum import ResultEnum
from ysgg1_club_comment.utils.camel_to_snake import camel_to_snake
from sqlalchemy import and_
from ..subject_serializers.label_serializer import LabelListSerializer, LabelSerializer


def get_label(label_id):
    subject_label = SubjectLabel.query.filter(
        and_(SubjectLabel.id == label_id, ~SubjectLabel.is_delete)).first()
    data = LabelSerializer(subject_label).to_dict()
    return {"code": 200, "message": "success", "data": data}


def query_label_by_category_id():
    request_json = request.json
    category_id = request_json.get('categoryId') if request_json.get('categoryId') else None

    label_list = SubjectLabel.query.filter_by(category_id=category_id, is_delete=0).all()
    label_data = LabelListSerializer(label_list).to_dict()

    return {"code": 200, "message": "查询成功", "data": label_data}


def add_label():
    try:
        parser = reqparse.RequestParser()
        parser.add_argument("labelName", type=str, required=True, help="标签名不能为空")
        parser.add_argument("sortNum", required=True, help="排序号不能为空")
        parser.add_argument("categoryId", required=True, help="categoryId不能为空")

        args = parser.parse_args()
        label_name = args["labelName"]
        sort_num = args["sortNum"]
        category_id = args["categoryId"]

        subject_label = SubjectLabel(label_name=label_name, category_id=category_id, sort_num=sort_num)
        db.session.add(subject_label)
        db.session.commit()
        current_app.logger.info("新增标签成功")
        return {"code": ResultEnum.success.code, "message": "新增标签成功", "data": True}
    except (OperationalError, SQLAlchemyError, Exception) as e:
        db.session.rollback()
        current_app.logger.error(json.dumps(e.__str__()))
        return {"code": ResultEnum.fail.code, "message": ResultEnum.fail.description}


def update_label(label_id):
    try:
        subject_label = SubjectLabel.query.filter(
            and_(SubjectLabel.id == label_id, ~SubjectLabel.is_delete)).first()
        if not subject_label:
            return {"code": ResultEnum.fail.code, "message": ResultEnum.fail.description}
        request_json = request.json
        for key, value in request_json.items():
            key = camel_to_snake(key)
            if hasattr(subject_label, key):
                setattr(subject_label, key, value)

        db.session.commit()
        current_app.logger.info("更新标签成功")
        return {"code": ResultEnum.success.code, "message": "更新标签成功", "data": 1}

    except (OperationalError, SQLAlchemyError, Exception) as e:
        db.session.rollback()
        current_app.logger.error(json.dumps(e.__str__()))
        return {"code": ResultEnum.fail.code, "message": ResultEnum.fail.description}


def delete_label(label_id):
    try:
        subject_label = SubjectLabel.query.filter(
            and_(SubjectLabel.id == label_id, ~SubjectLabel.is_delete)).first()
        if not subject_label:
            return {"code": ResultEnum.fail.code, "message": ResultEnum.fail.description}
        subject_label.is_delete = True
        db.session.commit()
        current_app.logger.info("删除标签成功")
        return {"code": ResultEnum.success.code, "message": "删除标签成功", "data": 1}

    except (OperationalError, SQLAlchemyError, Exception) as e:
        db.session.rollback()
        current_app.logger.error(json.dumps(e.__str__()))
        return {"code": ResultEnum.fail.code, "message": ResultEnum.fail.description}
